package com.tms.app.tms.ui.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.IdRes;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.tms.app.tms.R;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.app.MyApp;
import com.tms.app.tms.bean.GpsBean;
import com.tms.app.tms.bean.NotionBean;
import com.tms.app.tms.bean.UpdateInfo;
import com.tms.app.tms.bean.UserInfo;
import com.tms.app.tms.bean.response.UserInfoRes;
import com.tms.app.tms.db.TaskInfoDBUtil;
import com.tms.app.tms.service.AlarmService;
import com.tms.app.tms.service.UploadGPS;
import com.tms.app.tms.test.utils.ServiceUtil;
import com.tms.app.tms.ui.base.presenter.AbsServicexUtils;
import com.tms.app.tms.ui.base.presenter.BaseListPresenter;
import com.tms.app.tms.ui.base.presenter.ComPresenter;
import com.tms.app.tms.ui.base.ui.BaseListActivity;
import com.tms.app.tms.ui.home.history.TaskFt;
import com.tms.app.tms.ui.home.info.HomeFt;
import com.tms.app.tms.ui.home.market.MarketFt;
import com.tms.app.tms.ui.home.me.AboutMeFt;
import com.tms.app.tms.ui.home.msg.OrderFt;
import com.tms.app.tms.utils.ApkUpdate;
import com.tms.app.tms.utils.DownloadFileUtil;
import com.tms.app.tms.utils.LocationUtil;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.TimeUtil;
import com.tms.app.tms.utils.SysytemUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.shihao.library.XRadioGroup;

import static com.tms.app.tms.utils.TimeUtil.DEFAULT_DATE_FORMAT2;

/**
 * Created by Administrator on 2017/10/28 0028.
 */

public class MainActivity extends BaseListActivity implements AMapLocationListener, XRadioGroup.OnCheckedChangeListener {

    @BindView(R.id.nav_info)
    RadioButton navInfo;
    @BindView(R.id.nav_trade)
    RadioButton navTrade;
    @BindView(R.id.nav_market)
    RadioButton navMarket;
    @BindView(R.id.nav_history)
    RadioButton navHistory;
    @BindView(R.id.nav_c2c)
    RadioButton navC2c;

    @BindView(R.id.frame)
    FrameLayout frame;
    @BindView(R.id.nav_menu)
    XRadioGroup navMenu;
    @BindView(R.id.nav_msg_num)
    TextView navMsgNum;
    private HomeFt homeFt;// 任务
    private OrderFt orderFt;//消息
    private MarketFt marketFt;
    private TaskFt taskFt;//历史任务
    private AboutMeFt aboutFt;
    private Context context;
    private int showNav=-1;
    private long firstTime;
    private int radioIndex=R.id.nav_info;
    private double lat=0;
    private double lon=0;
    BaseListPresenter presenter=new BaseListPresenter();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
                if (TaskInfoDBUtil.checkTaskdoing()){
                    if (lat>0&&lon>0){
                        saveLocalGps(lat,lon);
                    }
                    presenter.uploadGps(token);
                }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_tms);
        if (savedInstanceState!=null){
            token=SharePreferenceUtil.getToken(this);
        }
        context = this;
        ButterKnife.bind(this);
        navMenu.setOnCheckedChangeListener(this);
        showFragment(0);
        mapLocationClient = LocationUtil.getLocationClient(this);
        mapLocationClient.setLocationOption(LocationUtil.initDefaultOption());
        mapLocationClient.setLocationListener(this);
        mapLocationClient.startLocation();
        presenter.getBDToken();

       // startService(new Intent(this, AlarmService.class));
        startService(new Intent(this, UploadGPS.class));
        ServiceUtil.startServiceIfDead(this, AlarmService.class);
        ServiceUtil.startServiceIfDead(this, UploadGPS.class);
        ApkUpdate.getUpdateInfo();
        getUserInfo();
        SharePreferenceUtil.setValue(this,"isEMUI",SysytemUtil.isEMUI());
        Timer timer = new Timer();
        timer.schedule(task,1000,1000*60*5);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        token=savedInstanceState.getString("token");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putString("token",token);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        showNav=getIntent().getIntExtra("showNav",-1);
        switch (showNav){
            case 0:
                navMenu.check(navInfo.getId());
                break;
            case 1:
                navMenu.check(navTrade.getId());
                break;
        }
    }



    /***
     * 获取用户资料
     */
    private void getUserInfo() {
        RequestParams params = new RequestParams(Constant.USER_INFO);
        params.addBodyParameter("token", token);
        params.addBodyParameter("showLoading", AbsServicexUtils.noShowAndHideLoading);
        new ComPresenter().getObjectFromServer(params, 1);
    }




    @Override
    protected void onStart() {
        super.onStart();
        showNotion(null);// 更新消息提醒
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
   public void  showNotion(NotionBean notionBean){
        if (radioIndex!=R.id.nav_trade){//
//            int num=SharePreferenceUtil.getInt(this,"tzhi",0);
//            int num2=SharePreferenceUtil.getInt(this,"tzhi-BG",0);
//            int num3=SharePreferenceUtil.getInt(this,"tzhi-XT",0);
//
//            num=num+num2+num3;
//            if (num>0){
//                navMsgNum.setText(num+"");
//                navMsgNum.setVisibility(View.VISIBLE);
//            }else {
//                navMsgNum.setVisibility(View.INVISIBLE);
//            }
        }else {//当前页是消息页时,任务全部已查看
            SharePreferenceUtil.setValue(context,"tzhi",0);
            SharePreferenceUtil.setValue(context,"tzhi-XT",0);
            SharePreferenceUtil.setValue(context,"tzhi-BG",0);
            navMsgNum.setVisibility(View.INVISIBLE);
        }

        int num=SharePreferenceUtil.getInt(this,"tzhi",0);
        int num2=SharePreferenceUtil.getInt(this,"tzhi-BG",0);
        int num3=SharePreferenceUtil.getInt(this,"tzhi-XT",0);
        num=num+num2+num3;
        if (num>0){
            navMsgNum.setText(num+"");
            navMsgNum.setVisibility(View.VISIBLE);
        }else {
            navMsgNum.setVisibility(View.INVISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void subscribe(String json) {
        UserInfoRes userInfoRes = gson.fromJson(json, UserInfoRes.class);
        if (userInfoRes.getCode() == 200) {
            if (userInfoRes.getData() != null && userInfoRes.getData() != null) {
                SharePreferenceUtil.saveObject(this, userInfoRes.getData());
            }

        }
    }


    public void showFragment(int checkedId) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        switch (checkedId) {
            case R.id.nav_info:
            case 0:
                if (homeFt == null) {
                    homeFt = new HomeFt();
                    ft.add(R.id.frame, homeFt);
                } else {
                    ft.show(homeFt);
                }
                break;
            case R.id.nav_trade:
            case 1:
                if (orderFt == null) {
                    orderFt = new OrderFt();
                    ft.add(R.id.frame, orderFt);
                } else {
                    ft.show(orderFt);
                }
                break;
            case R.id.nav_market:
            case 2:
                if (marketFt == null) {
                    marketFt = new MarketFt();
                    ft.add(R.id.frame, marketFt);
                } else {
                    ft.show(marketFt);
                }
                break;
            case R.id.nav_history:
            case 3:
                if (taskFt == null) {
                    taskFt = new TaskFt();
                    ft.add(R.id.frame, taskFt);
                } else {
                    ft.show(taskFt);
                }

                break;
            case R.id.nav_c2c:
            case 4:
                if (aboutFt == null) {
                    aboutFt = new AboutMeFt();
                    ft.add(R.id.frame, aboutFt);
                } else {
                    ft.show(aboutFt);
                }
                break;
        }
        ft.commitNow();
    }

    public void hideFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (homeFt != null)
            ft.hide(homeFt);
        if (orderFt != null)
            ft.hide(orderFt);
        if (marketFt != null)
            ft.hide(marketFt);
        if (taskFt != null)
            ft.hide(taskFt);
        if (aboutFt != null)
            ft.hide(aboutFt);
        ft.commitNow();
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        System.out.print("GPS："+aMapLocation.getLatitude());
        //  Toast.makeText(this, "服务定位成功", 1000).show();
        lat=aMapLocation.getLatitude();
        lon=aMapLocation.getLongitude();
        //  saveLocalGps(lat,lon);

    }

    public void saveLocalGps(Double lat,Double lon) {
        int planId = SharePreferenceUtil.getInt(this,"planId",0);
        UserInfo userInfo=SharePreferenceUtil.getObject(this, UserInfo.class);
//        if (userInfo!=null
//                &&userInfo.getId()>0&&userInfo.getHeadstockId()>0
//                &&userInfo.getTrailerId()>0&&planId>0){
            if (userInfo!=null
                    &&userInfo.getId()>0&&planId>0){
            GpsBean gpsBean=new GpsBean();
            gpsBean.setLat(lat+"");
            gpsBean.setLon(lon+"");
            gpsBean.setPlanId(planId);
            gpsBean.setDriverId(userInfo.getId());
            gpsBean.setCarId(userInfo.getHeadstockId());
            gpsBean.setTrailerId(userInfo.getTrailerId());
            long time= Long.parseLong(TimeUtil.getTime(new Date(),DEFAULT_DATE_FORMAT2));
            gpsBean.setTime(time);
            try {
                DbManager   db = x.getDb(MyApp.getDaoConfig());
                if (db == null)
                    return;
                db.save(gpsBean);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onCheckedChanged(XRadioGroup xRadioGroup, @IdRes int checkedId) {
        showNav=-1;
        radioIndex=checkedId;
        hideFragment();
        showFragment(checkedId);
        showNotion(new NotionBean());// 更新消息提醒

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN){
            if (System.currentTimeMillis()-firstTime>2000){
                Toast.makeText(MainActivity.this,"再按一次退出卡知佳",Toast.LENGTH_SHORT).show();
                firstTime=System.currentTimeMillis();
            }else{
                //clearLocalUserData();
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
